<template>
  <div class="login-wrap">
    <el-form label-position="top" :model="formData" :rules="rules" ref="loginForm" label-width="80px" class="login-form">
      <h3>管理员登录</h3>
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username">
        <el-input prefix-icon="iconfont icon-user" v-model="formData.username"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input prefix-icon="iconfont icon-showpassword" show-password v-model="formData.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">登录</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { loginApi } from '@/api/login'
// 自定义校验规则
const checkPassword = (rule, val, callback) => {
  const value = val.trim()
  const reg = /^\w{3,}$/
  if (!reg.test(value)) {
    return callback(new Error('密码必须是3位以上由字母、数字、下划线组成的'))
  }
  callback()
}
export default {
  data() {
    return {
      // 表单数据
      formData: {
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, message: '密码长度最少3个以上', trigger: 'blur' }
        ],
        password: [
          { validator: checkPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 表单提交
    submitForm() {
      // validate是进行表单校验的，valid是根据rules规则校验的结果(布尔类型)
      this.$refs.loginForm.validate(async valid => {
        if (!valid) {
          console.log('校验失败')
          return false
        }
        // 校验成功，发起登录校验
        const res = await loginApi(this.formData)
        if (res.meta.status !== 200) {
          return this.$message.error('登录失败:' + res.meta.msg)
        }
        // 保存token
        window.sessionStorage.setItem('token', res.data.token)
        window.sessionStorage.setItem('username', this.formData.username)
        this.$message({
          type: 'success',
          message: '登录成功',
          duration: 1000
        })
        this.$router.push('/')
      })
    },
    // 重置表单数据
    resetForm() {
      this.$refs.loginForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #324152;
  height: 100%;

  .login-form {
    background-color: #fff;
    width: 500px;
    padding: 30px;
    border-radius: 5px;
  }
}
</style>